using System;
using System.Web;
using ASPNETVN.PORTAL.Components.Helpers;
using ASPNETVN.PORTAL.Components.Security;
using ASPNETVN.PORTAL.Components.UI;

namespace ASPNETVN.PORTAL.Modules.SUPPORT.Controls
{
    public partial class AddEditMessage : AddEditItemControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack == false)
            {
                Components.Message message = Components.Message.GetLastest(this.ItemID);
                if (message != null)
                {
                    if (PortalSecurity.CurrentUser.Identity.Email == message.CreatedBy)
                    {
                        txtContent.Text = HttpUtility.HtmlDecode(message.Memo);
                    }
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                Components.Message message = new Components.Message();
                message.TopicID = this.ItemID;
                message.Memo = HttpUtility.HtmlEncode(txtContent.Text);
                message.CreatedBy = PortalSecurity.CurrentUser.Identity.Email;
                message.CreatedDate = DateTime.Now;

                Components.Message lastedMessage = Components.Message.GetLastest(this.ItemID);
                if (lastedMessage != null)
                {
                    if (PortalSecurity.CurrentUser.Identity.Email == lastedMessage.CreatedBy)
                    {
                        message.Update();
                    }
                    else
                    {
                        message.Insert();
                    }
                }
                
                string url = HttpUrlBuilder.BuildUrl(this.ModuleID, this.ItemID, ModulePages.Message);
                Response.Redirect(url);
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            string url = HttpUrlBuilder.BuildUrl(this.ModuleID, this.ItemID, ModulePages.Message);
            Response.Redirect(url);
        }
    }
}